#include <sys/types.h>
#include <errno.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>

uint32_t n;
#define MAX 100000
#define N_THREAD 8
pthread_mutex_t lock;

static void *work_thread(void *arg)
{
	int i = 0;
	while (i++ < MAX) {
		pthread_mutex_lock(&lock);
		n++;
		pthread_mutex_unlock(&lock);
	}
	printf("Thread %d: n = %u\n", *(int *)arg, n);
}


int main(int argc, char *argv[]) { // ./run [PORT] [rps filename] [len filename]

	int i = 0;
	int num_thread = N_THREAD;
	pthread_t thread_id[N_THREAD];
	int arg[N_THREAD];

	if (pthread_mutex_init(&lock, NULL)) {
		printf("Failed to create stack singal\n");
		exit(-1);
	}

	for (i = 0; i < num_thread; i++) {
		pthread_attr_t attr;
		int ret;
		pthread_attr_init(&attr);

		arg[i] = i;
		if ((ret = pthread_create(&thread_id[i], &attr, work_thread, &arg[i])) != 0) {
			printf("Can't create thread: %s\n", strerror(ret));
			exit(1);
		}
	}
	for (i = 0; i < num_thread; i++) {
		pthread_join(thread_id[i], NULL);
		printf("Thread %d join\n", i);
	}
	printf("Main thread: n = %lu\n", n);
}

